﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Windows.Forms;
using System.Drawing;
using Datagridview;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using System.IO;
using System.Net;
using System.Data;
using System.Data.OleDb;
using Microsoft.VisualBasic;
namespace QUANLYCHAMCONG.BL.BUS
{
    public class Common
    {
        private static int _flag = 0;

        public static int Flag
        {
            get { return Common._flag; }
            set { Common._flag = value; }
        }

        private static string _MaNV;

        public static string MaNV
        {
            get { return Common._MaNV; }
            set { Common._MaNV = value; }
        }
        public static void Remove(ref GroupBox gr)
        {
            foreach (Control c in gr.Controls)
            {
                if (c.Name.ToString() != "thanhcongcu")
                {
                    gr.Controls.Remove(c);
                    break;
                }
            }

        }
        public static void HightLightDataGridViewRow(ref DataGridView dgv, System.Data.DataTable dt)
        {
            // Setting the style of the DataGridView control
            dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point);
            dgv.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark;
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgv.DefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
            dgv.DefaultCellStyle.BackColor = Color.Empty;
            dgv.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
            dgv.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            dgv.GridColor = SystemColors.ControlDarkDark;

            // Binding the DataGridViewControl to the DataSet generated above
            dgv.DataSource = dt;
            // Changing the last column alignment to be in the Right alignment            
            dgv.Columns[dgv.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // Adjusting each column to be fit as the content of all its cells, including the header cell
            dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

            //MyDataGridView.Columns[0].Visible = false;
        }
        public static void HightLightDataGridViewRow(ref DevComponents.DotNetBar.Controls.DataGridViewX dgv , System.Data.DataTable dt)
        {
            // Setting the style of the DataGridView control
            dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma" , 9 , FontStyle.Bold , GraphicsUnit.Point);
            dgv.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark;
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgv.DefaultCellStyle.Font = new System.Drawing.Font("Tahoma" , 8 , FontStyle.Regular , GraphicsUnit.Point);
            dgv.DefaultCellStyle.BackColor = Color.Empty;
            dgv.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
            dgv.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            dgv.GridColor = SystemColors.ControlDarkDark;

            // Binding the DataGridViewControl to the DataSet generated above
            dgv.DataSource = dt;
            // Changing the last column alignment to be in the Right alignment            
            dgv.Columns [dgv.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // Adjusting each column to be fit as the content of all its cells, including the header cell
            dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

            //MyDataGridView.Columns[0].Visible = false;
        }
        public static void HightLightDataGridViewRow(ref CustomGrid dgv, System.Data.DataTable dt)
        {
            try
            {
                // Setting the style of the DataGridView control
                dgv.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point);
                dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.WhiteSmoke;
                dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
                dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgv.DefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);
                dgv.DefaultCellStyle.BackColor = Color.Empty;
                dgv.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight;
                dgv.CellBorderStyle = DataGridViewCellBorderStyle.Single;
                dgv.GridColor = SystemColors.ControlDarkDark;

                // Binding the DataGridViewControl to the DataSet generated above
                dgv.DataSource = dt;
                // Changing the last column alignment to be in the Right alignment            
                dgv.Columns[dgv.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;

                // Adjusting each column to be fit as the content of all its cells, including the header cell
                dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                //MyDataGridView.Columns[0].Visible = false;
            }
            catch {}
        }
        public static void AddComport(ref ComboBox cmb)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Hardware\DeviceMap\SerialComm");
            if (key != null)
            {
                string[] valueNames = key.GetValueNames();
                cmb.Items.Clear();
                foreach (string str in valueNames)
                {
                    string str2 = (string)key.GetValue(str);
                    if (!string.IsNullOrEmpty(str2))
                    {
                        cmb.Items.Add(str2);
                    }
                }
                cmb.SelectedIndex = 0;
            }
        }
        public static void CopyUSBDeviceDriversToSystem()
        {
            string sourceDirName = string.Format(@"{0}\USBDeviceDrivers\", Application.StartupPath);
            string destDirName = string.Format(@"{0}\drivers\", Environment.SystemDirectory);
            CopyDirectory(sourceDirName, destDirName);
        }
        public static void CopyDirectory(string sourceDirName, string destDirName)
        {
            if (sourceDirName.Substring(sourceDirName.Length - 1) != @"\")
            {
                sourceDirName = sourceDirName + @"\";
            }
            if (destDirName.Substring(destDirName.Length - 1) != @"\")
            {
                destDirName = destDirName + @"\";
            }
            if (Directory.Exists(sourceDirName))
            {
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }
                foreach (string str in Directory.GetFiles(sourceDirName))
                {
                    try
                    {
                        System.IO.File.Copy(str, destDirName + Path.GetFileName(str), true);
                    }
                    catch
                    {
                        break;
                    }
                }
                foreach (string str2 in Directory.GetDirectories(sourceDirName))
                {
                    CopyDirectory(str2, destDirName + str2.Substring(str2.LastIndexOf(@"\") + 1));
                }
            }
        }
        private static bool CreateAutoBackupFolder()
        {
            string path = Application.StartupPath + @"\BACKUP\";
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
            }
            return Directory.Exists(path);
        }
        public static IPAddress GetLocalIpAddress()
        {
            IPAddress address = null;
            try
            {
                foreach (IPAddress address2 in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if ((!address2.IsIPv6LinkLocal && !address2.IsIPv6Multicast) && !address2.IsIPv6SiteLocal)
                    {
                        address = address2;
                        if (address == null)
                        {
                            address = IPAddress.Parse("192.168.1.224");
                        }
                    }
                }
            }
            catch
            {
            }
            return address;
        }
        private bool Resizing = false;
        void lvdanhsach_SizeChanged(object sender, EventArgs e)
        {
            if (!Resizing)
            {
                // Set the resizing flag
                Resizing = true;
                ListView listView = sender as ListView;
                if (listView != null)
                {
                    float totalColumnWidth = 0;
                    // Get the sum of all column tags
                    for (int i = 0; i < listView.Columns.Count; i++)
                        totalColumnWidth += Convert.ToInt32(listView.Columns[i].Tag);

                    // Calculate the percentage of space each column should
                    // occupy in reference to the other columns and then set the
                    // width of the column to that percentage of the visible space.
                    for (int i = 0; i < listView.Columns.Count; i++)
                    {
                        float colPercentage = (Convert.ToInt32(listView.Columns[i].Tag) / totalColumnWidth);
                        listView.Columns[i].Width = (int)(colPercentage * listView.ClientRectangle.Width);
                    }
                }
            }

            // Clear the resizing flag
            Resizing = false;
        }
        public static DataTable GetExcelTable(string excelFilename)
        {
            string str2;
            string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=35;Extended Properties=Excel 8.0;Persist Security Info=False", excelFilename);
            DataSet dataSet = new DataSet();
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                str2 = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["Table_Name"].ToString();
                new OleDbDataAdapter("select * from [" + str2 + "]", connectionString).Fill(dataSet, str2);
                connection.Close();
            }
            return dataSet.Tables[str2];
        }
        public static List<string> GetExcelTableSchema(string excelFilename)
        {
            string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=35;Extended Properties=Excel 8.0;Persist Security Info=False", excelFilename);
            List<string> list = new List<string>();
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                string str2 = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["Table_Name"].ToString();
                object[] restrictions = new object[4];
                restrictions[2] = str2;
                foreach (DataRow row in connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, restrictions).Rows)
                {
                    string item = row["Column_Name"].ToString();
                    list.Add(item);
                }
                connection.Close();
            }
            return list;
        }
        public static DataTable InsertALL(DataTable dt,string DisplayMeber,string ValuesMember)
        {
            if (dt.Rows.Count != 0)
            {
                DataRow drow = dt.NewRow();
                drow[DisplayMeber] = dt.Rows[0][DisplayMeber];
                drow[ValuesMember] = dt.Rows[0][ValuesMember];
                dt.Rows.Add(drow);
                dt.Rows[0][DisplayMeber] = "All";
                dt.Rows[0][ValuesMember] = -1;
            }
            return dt;
        }
        public static void AddDataForCombobox(ref ComboBox cmb,ref DataTable dt,string DisplayMember,string ValuesMember)
        {
            cmb.DisplayMember = DisplayMember;
            cmb.ValueMember = ValuesMember;
            cmb.DataSource =InsertALL(dt,DisplayMember,ValuesMember);
        }
        public static void CheckAll(CheckBox chk, DataGridView luoi)
        {
            if (chk.CheckState == CheckState.Checked)
            {
                int num3 = luoi.Rows.Count - 1;
                for (int i = 0; i <= num3; i++)
                {
                    luoi.Rows[i].Cells[0].Value = true;
                }
            }
            else
            {
                int num4 = luoi.Rows.Count - 1;
                for (int j = 0; j <= num4; j++)
                {
                    luoi.Rows[j].Cells[0].Value = false;
                }
            }
        }
        /// <summary>
        /// khai bao  cho phan lam tron
        /// </summary>
        /// <param name="OriginMinute"></param>
        /// <returns></returns>
        public static int RoundStep = 15;
        public static int RoundType = 0;
       
        public static bool IsExists(string OrigFile)
        {
            bool flag;
            try
            {
                if (File.Exists(OrigFile))
                {
                    flag = true;
                }
                else
                {
                    flag = false;
                }
            }
            catch
            {
                flag=false;
            }
            return flag;
        }
        
    }
}
